home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part2 / 15770 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.9 KB

  1. Path: mail2news.demon.co.uk!genesis.demon.co.uk
  2. From: Lawrence Kirby <fred@genesis.demon.co.uk>
  3. Newsgroups: comp.lang.c
  4. Subject: Re: How to pass function as arg?
  5. Date: Sun, 21 Apr 96 12:04:21 GMT
  6. Organization: none
  7. Message-ID: <830088261snz@genesis.demon.co.uk>
  8. References: <317937f7.325108@news.csus.edu>
  9. Reply-To: fred@genesis.demon.co.uk
  10. X-NNTP-Posting-Host: genesis.demon.co.uk
  11. X-Newsreader: Demon Internet Simple News v1.27
  12. X-Mail2News-Path: genesis.demon.co.uk
  13.  
  14. In article <317937f7.325108@news.csus.edu> wleong@sfsu.edu "Jerry Leong" writes:
  15.  
  16. >Please don't flame me for asking this question as I have read the faq,
  17. >the newsgroup & I still couldn't find a satisfying answer.
  18. >
  19. >I couldn't quite figure out how to do this. Below is the pseudo-code :
  20. >
  21. >void do_something(void)
  22. >{
  23. >}
  24. >
  25. >void call_this(void func)
  26.  
  27. func need to be a pointer to a function, not simple void (void is not a
  28. valid type for any object). Use:
  29.  
  30.  void call_this(void (*func)(void))
  31.  
  32. As a function parameter you are allowed to write this more simply as:
  33.  
  34.  void call_this(void func(void))
  35.  
  36. but many people prefer the longer form for consistency and to show the
  37. pointer nature explicitly.
  38.  
  39. >{
  40. >   func();
  41.  
  42. Similarly some prefer the longer form to show a pointer is being dereferenced:
  43.  
  44.     (*func)();
  45.  
  46. >}
  47. >
  48. >main()
  49.  
  50. This form is valid but obsolete. Better style is:
  51.  
  52. int main(void)
  53.  
  54. >{
  55. >  void (*fp)() = do_something();
  56.  
  57. do_somthing() *calls* function do_something. You just want a pointer to it
  58. i.e.
  59.  
  60.    void (*fp)(void) = do_something;
  61.  
  62. If you prefer you can write the equivalent:
  63.  
  64.    void (*fp)(void) = &do_something;
  65.  
  66. >  call_this(fp);
  67.  
  68.    return 0;
  69.  
  70. >}
  71.  
  72. ...
  73.  
  74. >p/s: Could this be another good topic for FAQ??
  75.  
  76. I'm not convinced that is meets the "Frequently Asked" criterion.
  77.  
  78. -- 
  79. -----------------------------------------
  80. Lawrence Kirby | fred@genesis.demon.co.uk
  81. Wilts, England | 70734.126@compuserve.com
  82. -----------------------------------------
  83.